var os = require("os");
var fs = require("fs");
var http = require("http");
var path = require("path");

var express = require("express");
var serveIndex = require("serve-index");
var serveStatic = require("serve-static");

const multer = require("multer");

var argv = require("minimist")(process.argv.slice(2));

var folder = argv.r || argv._[0] || "./";
var http_port = argv.p || argv.port || 18080;
var http_host = argv.a || "0.0.0.0";

var ifaces = os.networkInterfaces();

process.title = "http-file-server";

function log(m) {
  console.log(m);
}

function getdatatime(timestamp) {
  if (timestamp != 0) var d = new Date(timestamp * 1000);
  else var d = new Date();
  return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + ":" + d.getMilliseconds();
}

var upload_dir = folder + "/upload/";

let fullPath = path.resolve(upload_dir);
let storage = multer.diskStorage({
  //设置文件存储路径
  destination: (req, file, cb) => {
    cb(null, fullPath);
  },
  //设置文件存储名称
  filename: (req, file, cb) => {
    console.log(file)
    if(req.upload_list == null)
    {
      req.upload_list = []
    }
    req.upload_list.push(file);
    cb(null, file.originalname);
  },
});
const upload = multer({ storage }).any();

function start() {
  var expressInstance = express();
  var application = http.createServer(expressInstance);

  expressInstance.all("*", (request, response, next) => {
    var date = getdatatime(0);
    var client = request.headers["x-forwarded-for"] || " " + request.socket.remoteAddress + ":" + request.socket.remotePort;
    log("[" + date + "] " + client + " <" + request.method + "> " + request.socket.localAddress + ":" + request.socket.localPort + "" + request.url);
    next();
  });

  expressInstance.get("/upload/form", function (req, res) {
    var p = '<form action="/upload/form" method="post" target="frame1" enctype="multipart/form-data">';
    p += '<p>file: <input type="file" name="file1" /> </p>';
    p += '<p><input type="submit" value="Upload" /></p></form>';
    p += "<iframe name=\"frame1\" frameborder=\"0\" width=\"100%\" height=\"100%\"></iframe>";
    res.send(p);
  });
  expressInstance.post("/upload/form", function (req, res, next) {
    upload(req, res, function (err) {
      if (err instanceof multer.MulterError) {
        // A Multer error occurred when uploading.
        res.send("multererr:" + err);
        console.log("multererr:", err);
      } else if (err) {
        // An unknown error occurred when uploading.
        res.send("err:" + err);
        console.log("err:", err);
      }
      var obj = 
      {
        state : 0,
        msg : err,
        upload : req.upload_list 
      }
      res.send( JSON.stringify(obj));
    });
  });

  //expressInstance.use(express.static(folder));
  //expressInstance.use(express.directory(folder));
  expressInstance.use("/", express.static(folder), serveIndex(folder, { icons: true, view: "details" }));

  application.listen(http_port, http_host, () => {
    log("Server start at http://" + http_host + ":" + http_port);
    log("Server rootdir " + folder);
    Object.keys(ifaces).forEach(function (dev) {
      ifaces[dev].forEach(function (details) {
        if (details.family === "IPv4") {
          log("> http://" + details.address + ":" + http_port);
        }
      });
    });
  });
}

start();

process.on("SIGINT", function () {
  log(process.title + "stopped.");
  process.exit();
});

process.on("SIGTERM", function () {
  log(process.title + "stopped.");
  process.exit();
});
